import daily.DateUtils
import daily.commons.CalendarView
import daily.core.Activity
import daily.core.Person
import daily.securety.Account
import grails.converters.JSON
import org.springframework.dao.DataIntegrityViolationException

class ActivityController {

    def list() {
        //默认应该返回当月的 TODO
        def date = new Date(params.date)
        def view = params.view
        def start = CalendarView."$view".getStart(date)
        def end =  CalendarView."$view".getEnd(date)
        def results = Activity.findAllByStartBetween(start, end)
        if (null == results) {
            render ''
            return
        }

        withFormat {
            html {
              return [activities: results]
            }
            'json' {
                render results as JSON
            }
        }

    }

    def save() {
        params.start = DateUtils.JavascriptDateToJavaDate(params.start)
        params.end = DateUtils.JavascriptDateToJavaDate(params.end)
        Activity activity = new Activity(params)
        activity.person = getCurrentPerson()
        if (!activity.validate()) {
            render view: 'error', model: [message: activity.errors]
            return;
        }
        activity.save(flush: true)
        render activity as JSON

    }

    def delete() {
        if (null == params.id) {
            render(status: 404, view: '/404')
            return;
        }

        Activity activity = Activity.findById(params.id);

        if (null == activity) {
            render (contentType: "text/json"){
                errorInfo = '不存在'
            }
            return;
        }

        activity.delete(flush: true)

        render (contentType: "text/json"){
            success = true
        }


    }

    private Account getCurrentAccount(){
        Account.findByName(session.accountName)
    }

    private Person getCurrentPerson(){
        getCurrentAccount().person
    }
}
